package es

import (
	"context"
	"encoding/json"
	"fmt"
	es "github.com/olivere/elastic/v7"
)

/**
es聚合
*/

func StatAggs(name string) {
	InitClient()

	statAgg := es.NewStatsAggregation().Field("age")
	resp, err := cli.Search(indexUser).
		Size(0).
		Aggregation(name, statAgg).Do(context.Background())

	CheckErr(err)

	data := resp.Aggregations[name]
	m := map[string]interface{}{}
	err = json.Unmarshal(data, &m)
	CheckErr(err)

	fmt.Println(m)
}

func TermsAggs(name string) {
	InitClient()

	termAgg := es.NewTermsAggregation().Field("age").Size(20)
	resp, err := cli.Search(indexUser).
		Size(0).
		Aggregation(name, termAgg).
		Do(context.Background())

	CheckErr(err)
	data := resp.Aggregations[name]
	m := map[string]interface{}{}
	err = json.Unmarshal(data, &m)
	CheckErr(err)

	fmt.Println(m)
}

func RangeAggs(name string) {
	InitClient()

	rangeAgg := es.NewRangeAggregation().
		Field("birthday").
		AddUnboundedFromWithKey("1", "2000-01-01").
		AddRangeWithKey("2", "2000-01-02", "2010-01-01").
		AddRangeWithKey("3", "2010-01-02", "2019-01-01").
		AddUnboundedToWithKey("4", "2020-01-01")

	resp, err := cli.Search(indexUser).
		Size(0).
		Aggregation(name, rangeAgg).
		Do(context.Background())

	CheckErr(err)

	data := resp.Aggregations[name]
	m := map[string]interface{}{}
	err = json.Unmarshal(data, &m)
	CheckErr(err)

	fmt.Println(m)
}
